package cn.it.shop.dao.impl;

import org.hibernate.classic.Session;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import cn.it.shop.dao.AccountDao;
import cn.it.shop.pojo.Account;

@Repository(value="accountDao")// 如果没有取名称默认就是accountServiceImpl
public class AccountDaoImpl extends BaseDaoImpl<Account> implements AccountDao{
	
	/*
	 * 根据用户名,查询当前用户信息,和它角色信息, 被查询的类必须实现UserDetails接口 此操作在项目中应该放到登陆成功之后调用
	 */
	public UserDetails loadUserByUsername(String login)
			throws UsernameNotFoundException {
		Session session = sessionFactory.getCurrentSession();
		return (Account) session
				.createQuery(
						"FROM Account a LEFT JOIN FETCH a.roleSet WHERE a.login=:login")//
				.setString("login", login)//
				.uniqueResult();
	}
	
	@Override
	public Account login(Account account) {
		Session session = sessionFactory.getCurrentSession();
		// roleSet里面的每一个role对象 在级联抓取privlegeSet集合
		return (Account)session.createQuery("FROM Account a LEFT JOIN FETCH a.roleSet r LEFT JOIN " +
				"FETCH r.privilegeSet WHERE a.login=:login AND a.pass=:pass")
			.setString("login",account.getLogin())//
			.setString("pass",account.getPass())//
			.uniqueResult();
	}

	@Override
	public void updateOnlyAccount(Account account) {
		String hql="UPDATE Account a SET a.login=:login,a.name=:name WHERE a.id=:id";
		Session session = sessionFactory.getCurrentSession();
		session.createQuery(hql)
			.setString("login", account.getLogin())//
			.setString("name", account.getName())//
			.setInteger("id", account.getId())//
			.executeUpdate();
	}

	@Override
	public Account getFetchRid(int id) {
		String hql="FROM Account a LEFT JOIN FETCH a.roleSet WHERE a.id=:id";
		Session session = sessionFactory.getCurrentSession();
		return (Account)session.createQuery(hql)//
				.setInteger("id", id)//
				.uniqueResult();
	}
}
